package com.weilx959.spt.core.component;

import com.jfoenix.controls.JFXTextArea;
import com.jfoenix.validation.base.ValidatorBase;
import com.weilx959.spt.core.config.FormControlConfig;
import com.weilx959.spt.core.utils.FXMLUtil;
import com.weilx959.spt.core.utils.Try;
import javafx.beans.DefaultProperty;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * TextArea表单项控制
 * 
 * @author weilx 
 * @since 2024年6月8日
 */
@Slf4j
@DefaultProperty("value")
public class TextAreaFormItemControl extends ValidatorFormItemControl<String> {
    private static final String XML = "/assets/fxml/component/text-area-form-control.fxml";

    @FXML
    private Label labelControl;

    @FXML
    private JFXTextArea textAreaControl;
    
    public TextAreaFormItemControl() {
        super();
        initialize();
    }
    
    @Override
    public Try<String> validate() {
        return Try.of(() -> {
            if (!textAreaControl.validate()) {
                throw new IllegalStateException(textAreaControl.getActiveValidator().getMessage());
            }
        });
    }

    @Override
    public boolean isModified() {
        return !StringUtils.equals(oldValue, getValue());
    }

    @Override
    public void setRowspan(int rowspan) {
        super.setRowspan(rowspan);
        double fontSize = textAreaControl.getFont().getSize();
        textAreaControl.setPrefRowCount((int)(FormControlConfig.ROW_HEIGHT * rowspan / (fontSize + 1)));
    }

    @Override
    public void addValidator(ValidatorBase... validator) {
        this.textAreaControl.setValidators(validator);
    }

    private void initialize() {
        // load
        FXMLUtil.loadControl(this, XML);
        // 输入框
        textAreaControl.textProperty().bindBidirectional(valueProperty());
        // default span
        setColspan(99);
        setRowspan(2);
    }
    
    // builder
    public static TextAreaFormItemControBuilder builder() {
        return new TextAreaFormItemControBuilder();
    }

    public static class TextAreaFormItemControBuilder
        extends ValidatorFormItemControlBuilder<String, TextAreaFormItemControl, TextAreaFormItemControBuilder> {
        @Override
        protected TextAreaFormItemControl newFormItemControl() {
            return new TextAreaFormItemControl();
        }

        @Override
        protected TextAreaFormItemControBuilder self() {
            return this;
        }
    }
}
